
import log from '../utils/logger'
import { MiddleWare } from '../types/types'
const chalk = require("chalk");

export type ResultInfo = {
  code: number;
  msg?: string;
  data?: any;
  err?: any
}
const whitelist: string[] = ["/", "/api/count", "/api/wx_openid", "/user/login"]
/**
 * 执行结果 handler 用来给每个响应对象包装响应码等
 */
export const ResultHandler: MiddleWare = () => async (ctx, next) => {

  if (whitelist.indexOf(ctx.request.url) !== -1) {
    log.warn("中间价1", ctx.body)
    // ctx.body = ctx.body
    await next()
  } else {
    // console.log("中间价1",ctx)

    // log.warn("中间价2",ctx.request)
    const r: ResultInfo = { code: 0 };
    try {
      log.warn(chalk.green('中间件3'), 1)
      const data: any = await next();
      log.warn(chalk.green('中间件3'), data)
      // if(!ctx.request.header.authorization){
      //   if(whitelist.indexOf(ctx.originalUrl) === -1 ){
      //       console.log("这个接口没有带token",ctx.originalUrl)
      //       ctx.throw(404,"404! api not found !",{ msg: "404! api not found !" })
      //   }
      // }
      r.code = 200;
      r.msg = 'success'
      r.data = data;
    } catch (err) {
      console.log("错误收集", err)
      log.error(err);
      log.error(ctx.request.url + ' 报错信息为：' + err.statusCode);
      r.code = err.statusCode
      switch (err.statusCode) {
        case 102:
          r.msg = "用户不存在";
          break;
        default:
          r.msg = err.msg;
          break;
      }
    }
    ctx.body = r;
  }


};